package com.xwj.nio.netty.echoserver;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.Scanner;

/**
 * @author xwj
 * @date 2020/6/15
 */
public class NettyEchoClient {
    private String serverIp;
    private Integer serverPort;

    public NettyEchoClient(String serverIp, Integer serverPort) {
        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }

    public void run() {
        // 创建反应器线程组
        // 负责IO事件的处理
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            // 设置反应器线程组
            b.group(workerGroup);
            // 设置io通道类型
            b.channel(NioSocketChannel.class);
            //设置监听端口
            b.remoteAddress(serverIp, serverPort);
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(NettyEchoClientHandler.INSTANCE);
                }
            });
            // 参数配置
            b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

            // 连接
            ChannelFuture f = b.connect();
            f.addListener(future -> {
                if(future.isSuccess()) {
                    System.out.println("客户端连接成功");
                } else {
                    System.out.println("客户端连接失败");
                }
            });
            // 阻塞，直到连接完成
            f.sync();

            Channel channel = f.channel();

            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入发送内容：");
            while(scanner.hasNext()) {
                //获取输入的内容
                String next = scanner.next();
                byte[] bytes = next.getBytes("UTF-8");
                ByteBuf buf = channel.alloc().buffer();
                buf.writeBytes(bytes);
                channel.writeAndFlush(buf);
                System.out.println("请输入发送内容：");
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new NettyEchoClient("127.0.0.1", 8888).run();
    }
}
